<!--
 * @Description:
 * @Author: hui
 * @Date: 2022-02-17 18:23:45
 * @LastEditTime: 2022-03-31 10:43:25
-->
<template>
	<div class="login">

		<div class="loginBox">
            <div class="login-left">
                <img src="../assets/images/login/login-left.png" class="logoLeftImg" />
            </div>
            <div class="login-info">
                <div class="logo-img"> <img src="../assets/images/login/logo.png" class="logo-icon"/> </div>
                <div class="form-style">
                    <el-form ref="loginFormRef" :model="loginForm" status-icon :rules="loginRules" class="demo-ruleForm">
                        <el-form-item  prop="name">
                            <el-input v-model="loginForm.name" autocomplete="off" maxlength="20" placeholder="请输入姓名" class="span10" @focus="handleFocus(`username`)" @blur="handleBlur(`username`)" @keyup="handleChangeInput">
                                <template #prefix>
                                    <img v-if="isActiveUsername"
                                        class="user-icon"
                                        src="../assets/images/login/user_active_icon.png"
                                        alt="" />
                                    <img v-else
                                        class="user-icon"
                                        src="../assets/images/login/user_icon.png"
                                        alt="" />
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item  prop="telephone">
                            <el-input v-model="loginForm.telephone" autocomplete="off" placeholder="请输入手机号" class="span10"  @focus="handleFocus(`phone`)" @blur="handleBlur(`phone`)"  @keyup="handleChangeInput">
                                <template #prefix>
                                    <img
                                        v-if="isActivePhone"
                                        class="user-icon"
                                        src="../assets/images/login/phone_active_icon.png"
                                        alt="" />
                                    <img v-else
                                        class="user-icon"
                                        src="../assets/images/login/phone_icon.png"
                                        alt="" />
                                </template>
                                <template #suffix>
                                        <span class="code-icon"></span>
                                        <span v-if="checkCodeBtn.isShow" class="code-date"> {{checkCodeBtn.text}}</span>
                                        <span v-else class="code-label" @click="handleSendCode" :disabled="checkCodeBtn.disabled">发送验证码----</span>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item  prop="verifyCode">
                            <el-input v-model="loginForm.verifyCode" type="code" autocomplete="off" placeholder="请输入验证码" class="span10" @focus="handleFocus(`code`)" @blur="handleBlur(`code`)"  @keyup="handleChangeInput">
                                <template #prefix>
                                    <img v-if="isActiveCode"
                                        class="user-icon"
                                        src="../assets/images/login/code_active_icon.png"
                                        alt="" />
                                    <img v-else
                                        class="user-icon"
                                        src="../assets/images/login/code_icon.png"
                                        alt="" />
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item class="span10 btn-login">
                            <el-button v-if="isShowLoginBtn" class="btn-login-active" type="primary" @click="submitForm(loginFormRef)"> 登录 </el-button>
                            <el-button v-else class="btn-login-disable" type="primary" disabled>登录</el-button>
                        </el-form-item>
                    </el-form>
                </div>

            </div>
		</div>
		<div class="myDialog">
			<el-dialog v-model="dialogVisible" title="首次登录请修改密码" width="500px" @close="dialogVisible = false">
				<el-form ref="formPassRef" :rules="formPassRules" :model="formPass" label-width="120px">
					<el-form-item label="新密码" prop="newpassword">
						<el-input v-model="formPass.newpassword" type="password" autocomplete="off" placeholder="请输入新密码 " />
					</el-form-item>
					<el-form-item label="确认新密码" prop="confirmpassword">
						<el-input v-model="formPass.confirmpassword" type="password" autocomplete="off" placeholder="请确认新密码" />
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button type="primary" class="save" size="small" @click="changeSubmitFn(formPassRef)"> 确 定 </el-button>
					</div>
				</template>
			</el-dialog>
		</div>
	</div>
</template>
<script setup lang="ts">
import { sendSms } from '@/ajax/index';
// import { usersPasswordchange } from '@/ajax/index';
import { isMoblePhoneRegular, isPassRegular } from '@/utils/regularCommon';
import type { ElForm } from 'element-plus';
import md5 from 'md5';
import { ComponentInternalInstance, reactive, ref } from 'vue';

import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
    const TIME_COUNT = 30;  //倒计时时间

	const { appContext } = getCurrentInstance() as ComponentInternalInstance;
	const proxy = appContext.config.globalProperties;
	type FormInstance = InstanceType<typeof ElForm>;
	// 路由
	const router = useRouter();
	// vuex
	const store = useStore();
	// 登录
	const loginFormRef = ref();
    const isActiveUsername = ref(false);
    const isActivePhone = ref(false);
    const isActiveCode = ref(false);
    const isShowLoginBtn = ref(false);
    let checkCodeBtn = reactive<any>({
      text: '',
      loading: false,
      disabled: false,
      duration: 60,
      timer: null,
      isShow: false
    })

	const loginForm = reactive({
		'name': ``,
		'password': `123456`,
        'telephone':``,
        'verifyCode':``,
	});
	const loginRules = {
		'name': [
			{
				'required': true,
				'message': `请输入姓名`,
				'trigger': `blur`
			},
			// { 'required': true, 'validator': isLoginRegular, 'trigger': `blur` }
		],
		'password': [
			{
				'required': true,
				'message': `请输入密码`,
				'trigger': `blur`
			},
			{ 'required': true, 'validator': isPassRegular, 'trigger': `blur` }
		],
        'telephone': [
			{
				'required': true,
				'message': `请输入手机号`,
				'trigger': `blur`
			},
			{ 'required': true, 'validator': isMoblePhoneRegular, 'trigger': `blur` }
		],
        'verifyCode': [
			{
				'required': true,
				'message': `请输入验证码`,
				'trigger': `blur`
			},
		]
	};
	// 登录函数
	const submitForm = (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.validate(valid => {
			if (valid) {
				const sendData = JSON.parse(JSON.stringify(loginForm));
				// sendData.password = md5(sendData.password);
				store
					.dispatch(`user/usersLoginAction`, {
						// 'grant_type': `password`,
						'name': sendData.name,
                        'telephone': sendData.telephone,
                        'verifyCode': sendData.verifyCode,
						// 'password': sendData.password,
						// 'scope': `all`,
						// 'client_id': `se`,
						// 'client_secret': `5536e62811f95b3e1a5fbede705f5218`
					})
					.then((res: any) => {
						if (res && res.options.token) {
							proxy.removeSession();
							// router.go(0);
                            if (res.content.companyId && res.content.status){
                                router.go(0);
                            } else {
                                router.push("/nocertified")
                            }
						}
						// if (res.succ) {
						// 	proxy.removeSession();
						// 	if (res.content.status === 0) {
						// 		router.go(0);
						// 	} else {
						// 		changePassword();
						// 	}
						// }
					});
			}
		});
	};
	// 修改密码弹框
	const formPassRef = ref();
	let formPass = reactive({
		'newpassword': ``,
		'confirmpassword': ``
	});
	const confirmPasswordFilter = (rule: any, value: any, callback: any) => {
		const fromData: any = formPass;
		if (fromData.newpassword && value !== fromData.newpassword) {
			callback(new Error(`两次输入的密码不一致！`));
		} else {
			callback();
		}
	};
	const isPassNoOdePass = (rule: any, value: any, callback: any) => {
		if (value === `123456`) {
			callback(new Error(`不能和初始密码一样！`));
		} else {
			callback();
		}
	};
	const formPassRules = {
		'newpassword': [
			{
				'required': true,
				'message': `请输入密码`,
				'trigger': `blur`
			},
			{
				'required': true,
				'validator': isPassNoOdePass,
				'trigger': `blur`
			},
			{
				'required': true,
				'validator': isPassRegular,
				'trigger': `blur`
			}
		],
		'confirmpassword': [
			{
				'required': true,
				'message': `请再次输入密码`,
				'trigger': `blur`
			},
			{
				'required': true,
				'validator': isPassNoOdePass,
				'trigger': `blur`
			},
			{
				'required': true,
				'validator': isPassRegular,
				'trigger': `blur`
			},
			{
				'required': true,
				'validator': confirmPasswordFilter,
				'trigger': `blur`
			}
		]
	};
	// 弹框
	const dialogVisible = ref(false);
	const changePassword = () => {
		formPass = {
			'newpassword': ``,
			'confirmpassword': ``
		};
		dialogVisible.value = true;
	};
    //跳转到注册页面
    const handleOpen = () =>{
		router.push(`/openfuxing`);
    };
    const handleFocus = (val: string)=>{
        if(val == 'username'){
            isActiveUsername.value = true
        }else if(val == 'phone'){
            isActivePhone.value = true
        }else if(val == 'code'){
            isActiveCode.value = true
        }
    }
    const handleBlur = (val: string)=>{
        if(val == 'username'){
            isActiveUsername.value = false
        }else if(val == 'phone'){
            isActivePhone.value = false
        }else if(val == 'code'){
            isActiveCode.value = false
        }
    }
    //
    const handleSendCode  = async () =>{
		const telephoneReg = /^1[3456789]\d{9}$/;
		if(!loginForm.telephone || !telephoneReg.test(loginForm.telephone)) {
			proxy.$message.warning(`请输入正确的手机号`);
			return false
		}
        // 倒计时期间按钮不能单击
		if (checkCodeBtn.duration !== 60) {
			checkCodeBtn.disabled = true
		}
		try {
			const res = await sendSms({mobile: loginForm.telephone});
			if (res.succ) {
				proxy.$message.success(`验证码发送成功`);
				dialogVisible.value = false;
				// 清除掉定时器
				checkCodeBtn.timer && clearInterval(checkCodeBtn.timer)
				// 开启定时器
				checkCodeBtn.timer = setInterval(() => {
					const tmp = checkCodeBtn.duration--
					checkCodeBtn.text = `${tmp}s后重新发送`
					checkCodeBtn.isShow = true
					if (tmp <= 0) {
						// 清除掉定时器
						clearInterval(checkCodeBtn.timer)
						checkCodeBtn.duration = 60
						checkCodeBtn.text = ''
						// 设置按钮可以单击
						checkCodeBtn.disabled = false
						checkCodeBtn.isShow = false
					}
					console.info(checkCodeBtn.duration)
				}, 1000)
			}
		} catch (error) {
			checkCodeBtn.disabled = false
			return Promise.reject(new Error(`cancel`));
		}
    }
    //input改变事件
    const handleChangeInput = ()=>{
        if(loginForm.name && loginForm.password && loginForm.verifyCode){
            isShowLoginBtn.value = true
        }else{
            isShowLoginBtn.value = false
        }
    }
	// 修改密码函数
	const changeSubmitFn = (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.validate(async valid => {
			if (valid) {
				const sentData = {
					'name': loginForm.name,
					'oldPassword': md5(loginForm.password),
					'password': md5(formPass.newpassword)
				};
				// await usersPasswordchange(sentData).then(async (res: any) => {
				// 	if (res.success) {
				// 		const resuleDat = { ...loginForm };
				// 		resuleDat.password = md5(formPass.newpassword);
				// 		store.dispatch(`user/usersLoginAction`, resuleDat).then((result: response) => {
				// 			if (result.success) {
				// 				if (result.content.status === 0) {
				// 					dialogVisible.value = false;
				// 					router.go(0);
				// 				}
				// 			}
				// 		});
				// 	}
				// });
			}
		});
	};
</script>
<style lang="scss" scoped>
	.login {
		@extend %relative;
		background: url(../assets/images/login/login-bg.png) no-repeat 100% 100%;
        background-size: cover;
        .login-left{
            width: 65%;
            .logoLeftImg{
                height: 100%;
                width: 100%;
                border-top-left-radius: 10px;
                border-bottom-left-radius: 10px;
            }
        }
		.loginBox {
            display: flex;
			width: 900px;
			height: 460px;
			position: absolute;
			top: 0;
			right: 0;
			bottom: 0px;
            left: 0;
			margin: auto;
			z-index: 1;
			// padding: 50px 30px 0;
			border: 1px solid $border_C;
			border-radius: 10px;
            background-color: #fff;
            .login-info{
                width: 50%;
                // margin-left: 50px;
                .logo-img{
                    text-align: center;
                }
                .logo-icon{
                    width: 84px;
                    margin: 50px 0;
                }
            }
            .form-style{
                margin-left: 50px;
            }
            .header-icon{
                z-index: 10000;
            }
            .login-remark{
                margin-left: 10px;
                color: #b1b3b8;
            }
            .code-date{
                color: #94979E;
            }
            .code-icon{
                display: inline-block;
                height: 20px;
                width: 1px;
                background-color: #E2E4E7;
                margin-top: 8px;
                margin-right: 10px;
            }

            .code-label{
                color: $project_them;
                cursor: pointer;
            }
            .zhuce-style{
                color: $project_them;
                cursor: pointer;
            }
			h4 {
				margin: 35px 0 30px 10px;
				font-size: 22px;
			}
			:deep(.el-form) {
				.el-form-item {
					background-color: transparent;
				}
				.el-form-item__content {
					background-color: transparent;
				}
				&:last-child {
					.el-button {
						width: 100%;
					}
				}
			}
            .btn-login{
                margin-top: 30px;
                .btn-login-active{
                    height: 36px;
                }
                .btn-login-disable{
                    height: 36px;
                    background-color: #C8C9CC;
                }
            }
            .user-icon{
                width: 16px;
                height: 16px;
                margin-top: 9px;
            }
            // .login-icon{
            //     position: absolute;
            //     left: 100px;
            // }
            ::v-deep .el-input__inner:focus {
                outline: 0;
                box-shadow: 0 0 0 1px #088D9E inset;
            }
        }
	}
</style>
